package com.zjitc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/10 16:39
 * @description:
 */
public class JedisProxy implements InvocationHandler {

    private JedisCommands target;
    private JedisPool pool;

    public JedisCommands getInstance(JedisPool pool){
      this.pool=pool;
      this.target=pool.getResource();
      Class clazz=target.getClass();
      Object object = Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
      return (JedisCommands)object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      try {
        return method.invoke(this.target,args);
      }finally {
        if (this.target instanceof Jedis){
          pool.returnResource((Jedis) target);
          System.out.println("release the jedis connection");
        }
      }
    }


    public static void main(String[] args){

    }
}
